﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace iPodBrake
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
        List<Queue> q = new List<Queue>();
        Queue currentItem;
        int ProcessID;
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fb = new FolderBrowserDialog();
            fb.ShowNewFolderButton = false;
            fb.Description = "Select location:";
            if (fb.ShowDialog() == DialogResult.OK)
            {
                AddToQueue(Utils.ReadFolder(fb.SelectedPath));
            }
            lblTotalFiles.Text = q.Count.ToString();
            if (q.Count > 0)
            {
                button2.Visible = true;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            lblTotalFiles.Text = q.Count.ToString();
            lblCurrentItem.Text = "";
            lblFPS.Text = "";
            lblFPS2.Visible = false;
            lblTimeEst.Text = "";
            statusStrip1.Visible = false;
        }
        private void StartProcess()
        {
            button2.Visible = false;
            btnAbort.Visible = true;
            Process hbProcess = new Process();
            hbProcess.StartInfo.FileName = Utils.FindHandBrake();
            hbProcess.StartInfo.UseShellExecute = false;
            hbProcess.StartInfo.CreateNoWindow = true;
            hbProcess.StartInfo.RedirectStandardOutput = true;
            hbProcess.StartInfo.RedirectStandardError = true;
            hbProcess.SynchronizingObject = this;
            hbProcess.StartInfo.Arguments = currentItem.HandBrakeArguments;
            hbProcess.EnableRaisingEvents = true;
            hbProcess.Exited += new EventHandler(hbProcess_Exited);
            hbProcess.OutputDataReceived += new DataReceivedEventHandler(hbProcess_OutputDataReceived);
            hbProcess.ErrorDataReceived += new DataReceivedEventHandler(hbProcess_ErrorDataReceived);

            hbProcess.Start();
            try
            {
                hbProcess.BeginOutputReadLine();
                hbProcess.BeginErrorReadLine();
            }
            catch
            {
            }
            ProcessID = hbProcess.Id;
        }
        private void NextItem()
        {
            if (q.Count > 0)
            {
                
                currentItem = q[0];
                lblCurrentItem.Text = currentItem.FileName;
                if ((!currentItem.Exists) || currentItem.OutputExists)
                {
                    q.RemoveAt(0);
                    NextItem();
                }
            }
            else
            {
                // Empty queue, work's finished!
                currentItem = null;
                button2.Visible = true;
            }
            lblTotalFiles.Text = q.Count.ToString();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            NextItem();
            if (currentItem != null)
            {
                StartProcess();
            }
        }
        private void hbProcess_Exited(object sender, EventArgs e)
        {
            Process hbProcess = (Process)sender;
            hbProcess.CancelErrorRead();
            hbProcess.CancelOutputRead();
            hbProcess.Close();
            if (currentItem != null)
            {
                q.RemoveAt(0);
                NextItem();
            }
            if (currentItem != null)
            {
                StartProcess();
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (currentItem != null)
                {
                    Abort();
                    e.Cancel = true;
                }

            }
            catch
            {
            }
        }
        private void Abort()
        {
            string partial = "";
            if (currentItem != null)
            {
                partial = currentItem.OutputFileName;
                StopProcess();
                while (File.Exists(partial))
                {
                    try
                    {
                        File.Delete(partial);
                    }
                    catch { }
                }
            }
            button2.Visible = true;
        }
        private void StopProcess()
        {
            Process hbProcess = Process.GetProcessById(ProcessID);


            try
            {
                hbProcess.Kill();
            }
            catch
            {
            }
            lblFPS.Text = "Finished";
            ProgressBar.Visible = false;
            currentItem = null;
            btnAbort.Visible = false;
            lblFPS.Text = "";
            lblFPS2.Visible = false;
            lblTimeEst.Text = "";
            statusStrip1.Visible = false;
            this.Text = "iPodBrake";
            currentItem = null;
            lblCurrentItem.Text = "";
        }
        private void AddToQueue(List<Queue> newItems)
        {
            foreach (Queue i in newItems)
            {
                if (File.Exists(i.OutputFileName))
                {
                    continue;
                }

                bool exists = false;
                foreach (Queue qi in q)
                {
                    if (qi.Path == i.Path && qi.FileName == i.FileName)
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists)
                    continue;
                q.Add(i);
            }
        }
        private void hbProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (currentItem == null)
                return;
            if (e.Data == null)
                return;
            //e.Data = "Encoding: task 1 of 1, 0.12 %"
            if (e.Data.StartsWith("Encoding:"))
            {
                string data = e.Data.Substring(22);
                string percentage = data.Substring(0, data.IndexOf("%"));
                lblPercentage.Text = percentage + " %";
                float fltProc = float.Parse(percentage.Replace(".", ","));
                ProgressBar.Value = (int)fltProc;
                ProgressBar.Visible = true;
                this.Text = percentage + " % - iPodBrake";
                
                if (data.IndexOf("(") > 0)
                {
                    data = data.Substring(data.IndexOf("("));
                    string fps = data.Substring(1, 5);
                    lblFPS.Text = fps;
                    lblTimeEst.Text = data.Substring(data.Length - 10).Replace(")", "");
                    lblFPS2.Visible = true;
                }
                string proc = e.Data.Substring(23, 5).Replace(".", ",");
                statusStrip1.Visible = true;

            }
        }
        private void hbProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            //lblFPS.Text = e.Data;
        }
        private void btnAbort_Click(object sender, EventArgs e)
        {
            Abort();
        }
    }
}
